package cn.tqfeiyang.springplus.framework.toolkit;

import cn.tqfeiyang.springplus.framework.response.ApiResult;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

public final class ResponseUtils {

    private static String UTF8 = "UTF-8";

    private static String CONTENT_TYPE = "application/json";

    public static void printError(HttpServletResponse response, String errorMessage) {
        printJson(response, ApiResult.failed(errorMessage));
    }

    public static void printJson(HttpServletResponse response, Object object) {
        response.setCharacterEncoding(UTF8);
        response.setContentType(CONTENT_TYPE);
        PrintWriter printWriter = null;
        try {
            printWriter = response.getWriter();
            printWriter.write(JsonUtils.toJsonString(object));
            printWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (printWriter != null) {
                printWriter.close();
            }
        }
    }

    public static void printString(HttpServletResponse response, String string) {
        response.setCharacterEncoding(UTF8);
        response.setContentType(CONTENT_TYPE);
        PrintWriter printWriter = null;
        try {
            printWriter = response.getWriter();
            printWriter.write(string);
            printWriter.flush();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (printWriter != null) {
                printWriter.close();
            }
        }
    }

    /**
     * 获取响应头数据
     *
     * @param response
     * @return JSON
     */
    public static String getHeadersJson(HttpServletResponse response) {
        Map<String, String> map = new HashMap<>();
        response.getHeaderNames().forEach(name -> {
            map.put(name, response.getHeader(name));
        });
        return map.size() > 0 ? JsonUtils.toJsonString(map) : null;
    }

}